package com.molyfun.parents.activity.common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.molyfun.parents.R;
import com.molyfun.parents.utils.BitmapUtil;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:24/10/2017.
 * <p>
 * 想用其他分享类型，后续完善
 */

public class ShareDialogActivity extends BaseActivity implements View.OnClickListener, WbShareCallback {

    private String TAG = "ShareDialogActivity";
    private static final int THUMB_SIZE = 150;

    @InjectView(R.id.share_wechat)
    ImageView mShareWechat;
    @InjectView(R.id.share_qq)
    ImageView mShareQQ;
    @InjectView(R.id.share_weibo)
    ImageView mShareWeibo;
    @InjectView(R.id.share_firends)
    ImageView mShareFirends;
    @InjectView(R.id.black_place)
    LinearLayout mBlackPlace;
//    boolean flage = false;

    public static final String WX_APP_ID = "wxc2211e378064bf1f";

    public static final String TENCENT_APP_ID = "1105972395";

    public static final String WEIBO_APP_ID = "1609946433";

    public static final String ACTIVITY_SHARE_TYPE_FLAG = "share_type";

    public static final String ACTIVITY_SHARE_TITLE_FLAG = "share_title";

    public static final String ACTIVITY_SHARE_CONTENT_FLAG = "share_content";

    public static final String ACTIVITY_SHARE_URL_FLAG = "share_url";

    private IWXAPI api;

    private int mCurrentShareType = ShareType.Type_TEXT;

    private String mCurrentPageUrl;

    private String mShareTitle;

    private String mShareContent;

    private WbShareHandler shareHandler;

    private Tencent mTencent;

    public interface ShareType {
        int Type_TEXT = 1001;
        int Type_IMG = 1002;
        int Type_Page = 1003;

    }

    public interface Constants {
    public static final String APP_KEY = "2045436852"; // 应用的APP_KEY
    public static final String REDIRECT_URL = "http://www.sina.com";// 应用的回调页
    public static final String SCOPE = // 应用申请的高级权限
    "email,direct_messages_read,direct_messages_write,"
        + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
        + "follow_app_official_microblog," + "invitation_write";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_dialog);

        ButterKnife.inject(this);
        mBlackPlace.setOnClickListener(this);
        mShareWechat.setOnClickListener(this);
        mShareFirends.setOnClickListener(this);
        mShareQQ.setOnClickListener(this);
        mShareWeibo.setOnClickListener(this);


        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        api.registerApp(WX_APP_ID);

        WbSdk.install(this, new AuthInfo(this, WEIBO_APP_ID, "http://molyfun.com/", "follow_app_official_microblog"));

        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();

        mTencent = Tencent.createInstance(TENCENT_APP_ID, ShareDialogActivity.this);

        mCurrentShareType = getIntent().getIntExtra(ACTIVITY_SHARE_TYPE_FLAG, ShareType.Type_TEXT);
        switch (mCurrentShareType) {
            case ShareType.Type_TEXT:
                break;
            case ShareType.Type_IMG:
                break;
            case ShareType.Type_Page:
                mCurrentPageUrl = getIntent().getStringExtra(ACTIVITY_SHARE_URL_FLAG);
                mShareTitle = getIntent().getStringExtra(ACTIVITY_SHARE_TITLE_FLAG);
                mShareContent = getIntent().getStringExtra(ACTIVITY_SHARE_CONTENT_FLAG);
                if(mShareContent.length() > 50){
                    mShareContent.substring(0, 48);
                    mShareContent += "...";
                }
                break;
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        shareHandler.doResultIntent(intent, this);
//        finish();
    }

    @Deprecated
    public static void shareText(Context context, String content) {
        Intent intent = new Intent();
        intent.setClass(context, ShareDialogActivity.class);
        intent.putExtra(ACTIVITY_SHARE_TYPE_FLAG, ShareType.Type_TEXT);
        intent.putExtra(ACTIVITY_SHARE_CONTENT_FLAG, content);
        context.startActivity(intent);
    }

    @Deprecated
    public static void shareImg(Context context, String imageUrl) {
        Intent intent = new Intent();
        intent.setClass(context, ShareDialogActivity.class);
        intent.putExtra(ACTIVITY_SHARE_TYPE_FLAG, ShareType.Type_IMG);
        context.startActivity(intent);
    }

    public static void sharePage(Context context, String title, String content, String url) {
        Intent intent = new Intent();
        intent.setClass(context, ShareDialogActivity.class);
        intent.putExtra(ACTIVITY_SHARE_TYPE_FLAG, ShareType.Type_Page);
        intent.putExtra(ACTIVITY_SHARE_CONTENT_FLAG, content);
        intent.putExtra(ACTIVITY_SHARE_TITLE_FLAG, title);
        intent.putExtra(ACTIVITY_SHARE_URL_FLAG, url);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.black_place:
                finish();
                break;
            case R.id.share_wechat:
                shareWeixin(false);
                break;
            case R.id.share_qq:
                shareQQ();
                break;
            case R.id.share_weibo:
                shareWeibo();
                break;
            case R.id.share_firends:
                shareWeixin(true);
                break;
        }
    }

    private void shareWeixin(boolean isFirendCircle) {
        switch (mCurrentShareType) {
            case ShareType.Type_TEXT:
                break;
            case ShareType.Type_IMG:
                break;
            case ShareType.Type_Page:
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = mCurrentPageUrl;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = mShareTitle;
                msg.description = mShareContent;
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                bmp.recycle();
                msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                if (!isFirendCircle) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                }
                api.sendReq(req);


                break;
        }
        finish();
    }

    private void shareWeibo() {
        switch (mCurrentShareType) {
            case ShareType.Type_TEXT:
                break;
            case ShareType.Type_IMG:
                break;
            case ShareType.Type_Page:

                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                weiboMessage.mediaObject = getWebpageObj();
                weiboMessage.textObject = getTextObj();
                shareHandler.shareMessage(weiboMessage, false);
                break;
        }
//        this.finish();
    }

    private void shareQQ() {
        switch (mCurrentShareType) {
            case ShareType.Type_TEXT:
                break;
            case ShareType.Type_IMG:
                break;
            case ShareType.Type_Page:
                onClickShare();

                break;
        }
//        finish();
    }

    private void onClickShare() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, mShareTitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mShareContent);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mCurrentPageUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://oa91iwip0.bkt.clouddn.com/ic_launcher.png");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "你好家长版");
        mTencent.shareToQQ(ShareDialogActivity.this, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                toast(R.string.errcode_share_success);
                finish();
            }

            @Override
            public void onError(UiError uiError) {
                toast(R.string.errcode_share_unknown);
            }

            @Override
            public void onCancel() {
                toast(R.string.errcode_share_cancel);
            }
        });
    }

    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = mShareContent;
        textObject.title = mShareTitle;
        textObject.actionUrl = mCurrentPageUrl;
        return textObject;
    }

    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = mShareTitle;
        mediaObject.description = mShareContent;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = mCurrentPageUrl;
        mediaObject.defaultText = "你好家长版";
        return mediaObject;
    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    public void onWbShareSuccess() {
        toast(R.string.errcode_share_success);
        finish();
    }

    @Override
    public void onWbShareCancel() {
        toast(R.string.errcode_share_cancel);
    }

    @Override
    public void onWbShareFail() {
        toast(R.string.errcode_share_unknown);
    }

}
